document.addEventListener('DOMContentLoaded', () => {
    // ID列排序（第1列）
    document.querySelector('#myTable th.sortable:nth-child(1)')?.addEventListener('click', function () {
        const asc = !this.classList.contains('sorted-asc');
        this.className = `sortable ${asc ? 'sorted-asc' : 'sorted-desc'}`;

        sortTable(0, (a, b) => asc ? a - b : b - a);
    });

    // 时间列排序（第3列）
    document.querySelector('#myTable th.sortable:nth-child(3)')?.addEventListener('click', function () {
        const asc = !this.classList.contains('sorted-asc');
        this.className = `sortable ${asc ? 'sorted-asc' : 'sorted-desc'}`;

        sortTable(2, (a, b) => asc ? a - b : b - a, parseTime);
    });

    // 通用排序函数
    function sortTable(colIndex, compareFn, parseFn = parseInt) {
        const tbody = document.querySelector('#myTable tbody');
        const rows = [...tbody.rows].sort((a, b) =>
            compareFn(
                parseFn(a.cells[colIndex].textContent),
                parseFn(b.cells[colIndex].textContent)
            )
        );
        tbody.replaceChildren(...rows);
    }

    // 时间解析函数
    function parseTime(str) {
        const [, bc, num] = str.match(/(?:(公元前))?(\d+)/) || [];
        return bc ? -num : +num;
    }
});